package tech.mhuang.pacebox.springboot.autoconfiguration.trace.mybatis;

import com.alibaba.fastjson.JSON;
import com.zaxxer.hikari.HikariDataSource;
import io.opentracing.Span;
import io.opentracing.Tracer;
import io.opentracing.tag.Tags;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;
import tech.mhuang.pacebox.core.date.DateTimeUtil;
import tech.mhuang.pacebox.core.dict.BasicDict;
import tech.mhuang.pacebox.core.exception.ExceptionUtil;
import tech.mhuang.pacebox.core.timer.SystemClock;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.core.util.ObjectUtil;
import tech.mhuang.pacebox.core.util.StringUtil;

import javax.sql.DataSource;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;

/**
 * mybatis配置
 *
 * @author mhuang
 * @since 1.0.0
 */
@Slf4j
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
public class TraceMybatisInterceptor implements Interceptor {

    private Tracer tracer;

    public TraceMybatisInterceptor(Tracer tracer) {
        this.tracer = tracer;
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        if (ObjectUtil.isNotEmpty(tracer.activeSpan())) {
            Object[] objects = invocation.getArgs();
            MappedStatement ms = (MappedStatement) objects[0];
            String id = ms.getId();
            int indexOf = id.lastIndexOf(".");
            Class clazz = Class.forName(id.substring(0, indexOf));
            String methodName = id.substring(indexOf + 1);
            for (Method method : clazz.getDeclaredMethods()) {
                if (StringUtil.equals(method.getName(), methodName)) {
                    IgnoreTrace ignoreTrace = method.getAnnotation(IgnoreTrace.class);
                    if (ignoreTrace == null) {
                        break;
                    }
                    return invocation.proceed();
                }
            }
            Span span = tracer.buildSpan(id)
                    .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT)
                    .start();
            try {
                BoundSql boundSql = ms.getBoundSql(objects[1]);
                DataSource dataSource = ms.getConfiguration().getEnvironment().getDataSource();
                Tags.DB_TYPE.set(span, "sql");
                if (dataSource instanceof HikariDataSource) {
                    HikariDataSource hikariDataSource = (HikariDataSource) dataSource;
                    Tags.DB_INSTANCE.set(span, hikariDataSource.getJdbcUrl());
                    Tags.DB_USER.set(span, hikariDataSource.getUsername());
                }
                BasicDict sqlDict = showSql(ms.getConfiguration(), boundSql);
                Tags.DB_STATEMENT.set(span, sqlDict.get("sql", String.class));
                span.setTag("db.params", JSON.toJSONString(sqlDict.get("params")));
                /**
                 * 输出日志
                 */
                long start = SystemClock.now();
                Object proceed = invocation.proceed();
                long end = SystemClock.now();
                BasicDict basicDict = new BasicDict();
                basicDict.set(((end - start) / 1000) + "s", JSON.toJSONString(proceed));
                span.log(basicDict);
                return proceed;
            } catch (Exception e) {
                Tags.ERROR.set(span, Boolean.TRUE);
                Map<String, String> log = ExceptionUtil.logsForException(e);
                log.put("event", Tags.ERROR.getKey());
                span.log(log);
                throw e;
            } finally {
                span.finish();
            }
        }
        return invocation.proceed();
    }


    private static String getParameterValue(Object obj) {
        String value;
        if (obj instanceof String) {
            value = new StringBuilder().append("'").append(obj.toString()).append("'").toString();
        } else if (obj instanceof Date) {
            value = new StringBuilder().append("'").append(DateTimeUtil.fromDateTime(LocalDateTime.now())).append("'").toString();
        } else {
            if (obj != null) {
                value = obj.toString();
            } else {
                value = "";
            }

        }
        return value;
    }

    public static BasicDict showSql(Configuration configuration, BoundSql boundSql) {
        BasicDict basicDict = new BasicDict();
        // 获取参数
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql
                .getParameterMappings();
        // sql语句中多个空格都用一个空格代替
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        BasicDict paramDict = new BasicDict();

        if (CollectionUtil.isNotEmpty(parameterMappings) && parameterObject != null) {
            // 获取类型处理器注册器，类型处理器的功能是进行java类型和数据库类型的转换<br>　　　　　　　// 如果根据parameterObject.getClass(）可以找到对应的类型，则替换
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                String paramValue = Matcher.quoteReplacement(getParameterValue(parameterObject));
                paramDict.set(parameterMappings.get(0).getProperty(), paramValue);
                sql = sql.replaceFirst("\\?", paramValue);
            } else {
                // MetaObject主要是封装了originalObject对象，提供了get和set的方法用于获取和设置originalObject的属性值,主要支持对JavaBean、Collection、Map三种类型对象的操作
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    if (metaObject.hasGetter(propertyName)) {
                        Object obj = metaObject.getValue(propertyName);
                        String paramValue = Matcher.quoteReplacement(getParameterValue(obj));
                        paramDict.set(propertyName, paramValue);
                        sql = sql.replaceFirst("\\?", paramValue);
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        // 该分支是动态sql
                        Object obj = boundSql.getAdditionalParameter(propertyName);
                        String paramValue = Matcher.quoteReplacement(getParameterValue(obj));
                        paramDict.set(propertyName, paramValue);
                        sql = sql.replaceFirst("\\?", paramValue);
                    } else {
                        sql = sql.replaceFirst("\\?", "缺失");
                    }
                    //打印出缺失，提醒该参数缺失并防止错位
                }
            }
        }
        basicDict.set("sql", sql);
        basicDict.set("params", paramDict);
        return basicDict;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
